# this script plots the evolution of a spike in the Prinz model.

from Prinz_classes import *
from pylab import *

# prompt the user to pick a config filename
config = pick_config()

# find out if the cell has a previous simulation run
found_previous = False
listing = os.listdir('.')
for file in listing:
    if config[1] == file:
        c = Ccell.from_data_file( file+'/cell_data.cPickle')
        found_previous = True
        print "We've found that this cell has been simulated previously for %d ms." % (c.total_time)
if not found_previous:
    c = Ccell(config_filename = config[0])
    c.exercise(i_time = 500)

def plot_range(start_time,end_time,figure_number):
    if end_time > c.total_time:
        i_time = end_time - c.total_time
        c.exercise(X_init = c.X[-1],timestep = c.dt, i_time = i_time)


    start_i = start_time/c.dt
    end_i = end_time/c.dt

    figure(figure_number)
    
    # construct the title of the plot
    title_string = 'Maximal conductances in mS/cm^2 \n '
    item_count = 0
    for ID in c.set_channels.keys():
        prefix = c.ID_has_prefix(ID)
        name = prefix[2:] + ": "
        conductance = c.conductances[c.channels.index(ID)]
        title_string = title_string + name + str(conductance) + '  '    
    title_string = title_string + 'leak: ' + str(c.leak_conductance)

    subplot(311)
    title(title_string,fontsize=12)
    plot(c.t[start_i:end_i],c.V_trace()[start_i:end_i])
    ylabel('Voltage (mV)')
    setp(gca(),xticks=[])
    yticks(fontsize=10)
    #subplot(312)
    #plot(c.t[start_i:end_i],c.Ca_trace()[start_i:end_i])
    #setp(gca(),xticks=[])
    subplot(312)
    # plot the two most important currents for the generation of an action potential
    plot(c.t[start_i:end_i],c.currents['I_Na']['trace'][start_i:end_i],c.t[start_i:end_i],c.currents['I_Kd']['trace'][start_i:end_i] ) 
    ylabel('Current (nA)')
    legend(('Na','Kd'),5)
    # only show the xticks on the bottom plot
    setp(gca(),xticks=[])
    yticks(fontsize=10)

    # plot the rest of the currents
    subplot(313)
    plot(c.t[start_i:end_i],c.currents['I_CaT']['trace'][start_i:end_i],c.t[start_i:end_i],c.currents['I_CaS']['trace'][start_i:end_i],c.t[start_i:end_i],c.currents['I_KCa']['trace'][start_i:end_i],c.t[start_i:end_i],c.currents['I_KA']['trace'][start_i:end_i],c.t[start_i:end_i],c.currents['I_H']['trace'][start_i:end_i])
    legend(('CaT','CaS','KCa','KA','H'),5)
    yticks(fontsize=10)
    ylabel('Current (nA)')
    xlabel('time (ms)')


# plot out the whole time simulated for first.
figure_count = 0
print "Plotting results"
plot_range(0,c.total_time,figure_count)
show()
